<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>编辑商品SKU</title>
  <link href="../../static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
  <link href="../../static/vendor/bootstrap-icons/bootstrap-icons.min.css" rel="stylesheet">
  <link href="../../static/css/vui365.min.css" rel="stylesheet">
  <style>
    #skuListContainer input[type="search"] {
      width: 100px !important;
    }

    #skuListContainer .col {
      border: 1px solid #efefef;
    }

    .btn-toggle {
      color: #999
    }

    td a img {
      width: 27px;
      height: 27px;
    }
  </style>
</head>

<body>
  <div id="app">
    <form class="form-main form-horizontal" style="height:100vh" method="POST" ref="editForm">
      <div class="form-body container-fluid p-3"
        style="height:calc(100% - 45px); overflow-y: auto; overflow-x: hidden;">
        <div class="sku">
          <div class="sku-container">
            <label class="form-label">商品 SKU 列表</label>
            <div class="mt-1">
              <div class="input-group input-group-sm mb-1">
                <span class="input-group-text">批量设置：</span>
                <input type="search" class="form-control form-control-sm" placeholder="价格" title="价格"
                  v-model="batchFillData.price" />
                <input type="search" class="form-control form-control-sm" placeholder="数量" title="数量"
                  v-model="batchFillData.quantity" />
                <button class="btn btn-sm btn-secondary" @click.prevent="onBatchFill()">
                  立即设置
                </button>
              </div>
              <div id="skuListContainer" style="width: 100%; overflow: auto">
                <table class="table table-sm table-bordered">
                  <thead>
                    <tr>
                      <th>#</th>
                      <th class="text-nowrap">
                        批号（过期时间）
                      </th>
                      <th class="text-nowrap">价格</th>
                      <th class="text-nowrap">数量</th>
                      <th class="text-nowrap">默认选中</th>
                      <th class="text-nowrap">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(item, idx) of dataOfSku" :key="idx">
                      <td>{{ idx + 1 }}</td>
                      <td>
                        <input class="form-control form-control-sm" type="date" placeholder="批号（过期时间）"
                          v-model="item['sku_no']" @input="onInputDate($event,idx)" required />
                      </td>
                      <td>
                        <input class="form-control form-control-sm" type="number" placeholder="价格"
                          v-model="item['price']" required min="0" />
                      </td>
                      <td>
                        <input class="form-control form-control-sm" type="number" placeholder="数量"
                          v-model="item['quantity']" required min="0" />
                      </td>
                      <td>
                        <input type="radio" name="is_default" value="1" v-model="item['is_default']" />
                      </td>
                      <td>
                        <button class="btn btn-sm btn-secondary" @click.prevent="onAddSku(idx)">添加</button>
                        <button class="btn btn-sm btn-secondary" @click.prevent="onRemoveSku(idx)">删除</button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
        <!-- /.form-body -->
      </div>
      <div class="form-footer border-top pt-2 w-100 text-end">
        <button type="button" class="btn btn-secondary" @click.prevent="onCancelHandle()">取消</button>
        <cd-button class="btn btn-primary mx-2" @click="onSubmitHandle()">保存</cd-button>
      </div>
    </form>
    <input type="file" ref="file" style="display: none;" />
  </div>

  <script src="../../static/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="../../static/vendor/vue/vue.global.prod.min.js"></script>
  <script>
    // 全局配置
    this.vui365 = this.parent.vui365;

    // API接口配置
    const UrlCfg = {
      show: '/api/admin/ec-goods/{id}', // GET
      update: '/api/admin/ec-goods/update-sku/{id}', // POST
      upload: '/api/admin/uploader', // POST
    }
    /**
     * 管理员组件
     * @description 管理员组件
     */
    const App = {
      // data 配置
      data() {
        return {
          id: 0,
          dataOfMain: {
            data: {},
            status_data: []
          },
          // 商品的SKU数据
          dataOfSku: [],
          // 默认SKU数据
          dataOfDefaultSkuItem: {
            sku_no: '',
            expire_date: '',
            price: 0,
            quantity: 0,
            is_default: 0,
          },
          // 批量设置数据
          batchFillData: { price: "", quantity: "" },
        };
      },
      // methods 配置
      methods: {
        // 初始化页面数据
        initData() {
          this.loadFormData();
        },
        // 初始化页面视图
        initView() {
          // 移除骨架屏
          document.querySelectorAll('.skeleton').forEach(el => {
            el.classList.remove("skeleton");
          })
        },
        // 加载表单数据
        async loadFormData() {
          vui365.globalApp.showLoading();
          const msgInfo = await vui365.stdAxios(UrlCfg.show.replace('{id}', this.id), { _mode: 'sku' }, 'GET');
          vui365.globalApp.hideLoading();
          console.log("[加载表单数据] msgInfo=", this.id, msgInfo);
          if (msgInfo.status == 0) {
            alert(msgInfo.message);
            return;
          }
          this.dataOfMain = msgInfo.data;
          this.dataOfSku = msgInfo.data.skus_data;
          if (this.dataOfSku.length == 0) {
            this.dataOfSku.push(Object.assign({}, this.dataOfDefaultSkuItem))
          }
          // console.log("[加载表单数据] data=", this.dataOfMain);
        },
        // 处理表单提交事件
        async onSubmitHandle() {
          let elForm = document.querySelector("form");
          // 表单原生校验方法
          if (!elForm.checkValidity()) {
            elForm.reportValidity();
            return;
          }
          let data = {
            sku_data: this.dataOfSku,
            _mode: 'losku',
          }
          let msgInfo = await vui365.stdAxios(UrlCfg.update.replace('{id}', this.id), data, 'POST');

          console.log("[提交表单] msgInfo=", msgInfo, data);
          if (msgInfo.status == 0) {
            if (typeof msgInfo.message == "object") {
              let messageArr = [];
              for (let k in msgInfo.message) {
                msgInfo.message[k].forEach((text) => {
                  messageArr.push(text);
                });
              }
              msgInfo.message = messageArr.join("<br />");
            }
            vui365.BsDialog.alert(msgInfo.message);
            console.log('显示错误');
            return;
          }

          console.log('刷新表格');
          vui365.globalApp.closeFormDialog();
          vui365.globalApp.refreshDataTable()
        },
        // 选择日期
        onInputDate($event, idx) {
          let value = $event.target.value;
          this.dataOfSku[idx].sku_no = value;
          this.dataOfSku[idx].expire_date = value;
          console.log(this.dataOfSku);
        },
        // 添加日期
        onAddSku(idx) {
          this.dataOfSku.splice(idx, 0, Object.assign({}, this.dataOfDefaultSkuItem));
        },
        // 删除日期
        onRemoveSku(idx) {
          this.dataOfSku.splice(idx, 1)
          if (this.dataOfSku.length == 0) {
            this.dataOfSku.push(Object.assign({}, this.dataOfDefaultSkuItem));
          }
        },
        // 批量设置值
        onBatchFill() {
          this.dataOfSku.forEach((item) => {
            for (let k in this.batchFillData) {
              item[k] = this.batchFillData[k];
            }
          });
        },
      },
      // created 生命周期方法
      created() {
        this.id = vui365.EsUtils.getQueryString("id", 0, window.location.search);
        this.initData();
      },
      // mounted 生命周期方法
      mounted() {
        this.initView();
      },
    };

    // 创建应用实例
    const app = Vue.createApp(App);
    //  注册组件
    app.component("CdButton", vui365.getComponentOfCdButton())
    // 加载根元素
    app.mount('#app');
  </script>

</body>

</html>